<!--
 * @Author: 涵崽
 * @Date: 2023-12-06 15:29:50
 * @email: 1045654@qq.com
 * @gitee: https://gitee.com/han-zai
 * @LastEditors: 涵崽
 * @LastEditTime: 2023-12-06 15:45:55
 * @Description: 微信：1045654
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        width: 100vw;
      }
    </style>
  </head>
  <body>
    <input type="file" id="fileInput" accept="image/*" />
    <canvas id="canvas" style="display: none"></canvas>
    <img id="targetImage" />
    <img alt="水印图" id="waterMark" />
    <canvas id="mergedCanvas" style="display: none"></canvas>
    <script>
      const fileInput = document.getElementById("fileInput");
      const canvas = document.getElementById("canvas");
      const targetImage = document.getElementById("targetImage");
      const waterMark = document.getElementById("waterMark");
      const mergedCanvas = document.getElementById("mergedCanvas");

      // 监听文件输入改变事件
      fileInput.addEventListener("change", function (e) {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = function (event) {
          // 创建图像对象
          const img = new Image();
          img.onload = function () {
            // 创建canvas并设置其大小与图片一致
            canvas.width = img.width;
            canvas.height = img.height;
            // 在canvas上绘制水印图片
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            // 在canvas上添加文字水印，具体样式和位置请自行调整
            ctx.font = "bolder 20px Verdana";
            ctx.textAlign = "center";
            ctx.strokeStyle = "#fff";
            ctx.strokeText("@涵崽", img.width / 2, img.height - 10);
            // 将canvas转为base64格式的图片
            const base64 = canvas.toDataURL("image/jpeg");
            console.log(base64);
            // 将上传的图片转为base64格式的图片，并设置为targetImage的src
            targetImage.src = event.target.result;
            waterMark.src = base64;
          };
          img.src = event.target.result;
        };
        reader.readAsDataURL(file);
      });
    </script>
  </body>
</html>
